package com.example.mydy;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.adapter.ProjectAdapter;
import com.example.mydy.fragment.ProjectDialogFragment;
import com.example.mydy.model.Project;
import com.example.mydy.model.UserData;
import com.example.mydy.utils.ImageLoader;
import com.example.mydy.utils.MockDataManager;
import com.example.mydy.utils.SharedPreferencesManager;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class ProjectActivity extends AppCompatActivity implements ProjectAdapter.OnProjectActionListener, 
        ProjectDialogFragment.ProjectUnlockListener {
    private static final String TAG = "ProjectActivity";

    private RecyclerView recyclerView;
    private ProjectAdapter adapter;
    private ProgressBar progressBar;
    private TextView noProjectsText;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TextView userBalanceText, taskRewardTodayText, subTaskRewardText, inviteCountText;
    private Button btnCategoryAll, btnCategoryNew, btnCategoryHot, btnCategoryUnlocked;

    private String currentUsername;
    private UserData userData;
    private List<Project> projectList = new ArrayList<>();
    private DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private String currentCategory = "all";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project);
    
        // 初始化工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        
        // 获取当前用户
        currentUsername = SharedPreferencesManager.getUsername(this);
        
        // 初始化视图
        initViews();
        
        // 加载用户数据
        loadUserData();
        
        // 加载项目列表
        loadProjects();
        
        // 设置下拉刷新
        setupSwipeRefresh();
        
        // 设置底部导航
        setupBottomNavigation();
        
        // 设置分类按钮
        setupCategoryButtons();
    }
    
    private void initViews() {
        recyclerView = findViewById(R.id.project_recycler_view);
        progressBar = findViewById(R.id.progress_bar);
        noProjectsText = findViewById(R.id.tv_no_projects);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        userBalanceText = findViewById(R.id.userBalance);
        taskRewardTodayText = findViewById(R.id.taskRewardToday);
        subTaskRewardText = findViewById(R.id.subTaskReward);
        inviteCountText = findViewById(R.id.inviteCount);
        btnCategoryAll = findViewById(R.id.btn_category_all);
        btnCategoryNew = findViewById(R.id.btn_category_new);
        btnCategoryHot = findViewById(R.id.btn_category_hot);
        btnCategoryUnlocked = findViewById(R.id.btn_category_unlocked);
        
        // 设置项目列表网格布局
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    }
    
    private void loadUserData() {
        userData = MockDataManager.getUserDataStatic(currentUsername);
        if (userData != null) {
            userBalanceText.setText(decimalFormat.format(userData.getBalance()));
            taskRewardTodayText.setText(String.format("%.2f", userData.getDailyTaskReward()));
            subTaskRewardText.setText(String.format("%.2f", userData.getDailySubTaskReward()));
            inviteCountText.setText(String.valueOf(userData.getInviteCount()));
        } else {
            Log.e(TAG, "获取用户数据失败: " + currentUsername);
            Toast.makeText(this, "获取用户数据失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void loadProjects() {
        progressBar.setVisibility(View.VISIBLE);
        
        // 从数据管理器获取项目列表
        projectList = MockDataManager.getProjects();
        
        // 更新UI
        if (projectList.isEmpty()) {
            noProjectsText.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            noProjectsText.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            
            // 创建并设置适配器
            if (adapter == null) {
                adapter = new ProjectAdapter(this, projectList, currentUsername, this);
                recyclerView.setAdapter(adapter);
            } else {
                adapter.updateData(projectList);
            }
            
            // 应用当前分类过滤
            filterProjectsByCategory();
        }
        
        progressBar.setVisibility(View.GONE);
        swipeRefreshLayout.setRefreshing(false);
    }
    
    private void setupSwipeRefresh() {
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
        swipeRefreshLayout.setOnRefreshListener(this::loadProjects);
    }
    
    private void setupBottomNavigation() {
        // 使用BottomNavigationView而不是单独的View
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        if (bottomNavigationView != null) {
            bottomNavigationView.setOnItemSelectedListener(item -> {
                int itemId = item.getItemId();
                if (itemId == R.id.nav_home) {
                    // 先设置选中项为首页，然后再跳转
                    bottomNavigationView.setSelectedItemId(R.id.nav_home);
                    startActivity(new Intent(this, MainActivity.class));
                    finish();
                    return true;
                } else if (itemId == R.id.nav_advertisement) {
                    // 先设置选中项为广告，然后再跳转
                    bottomNavigationView.setSelectedItemId(R.id.nav_advertisement);
                    startActivity(new Intent(this, AdvertisementListActivity.class));
                    finish(); // 添加finish()调用确保当前页面被销毁
                    return true;
                } else if (itemId == R.id.nav_project) {
                    // 当前页面
                    return true;
                } else if (itemId == R.id.nav_my) {
                    // 先设置选中项为我的，然后再跳转
                    bottomNavigationView.setSelectedItemId(R.id.nav_my);
                    startActivity(new Intent(this, MyActivity.class));
                    finish();
                    return true;
                }
                return false;
            });
            
            // 设置当前选中项
            bottomNavigationView.setSelectedItemId(R.id.nav_project);
        }
    }
    
    private void setupCategoryButtons() {
        btnCategoryAll.setOnClickListener(v -> {
            updateCategorySelection("all");
        });
        
        btnCategoryNew.setOnClickListener(v -> {
            updateCategorySelection("new");
        });
        
        btnCategoryHot.setOnClickListener(v -> {
            updateCategorySelection("hot");
        });
        
        btnCategoryUnlocked.setOnClickListener(v -> {
            updateCategorySelection("unlocked");
        });
    }
    
    private void updateCategorySelection(String category) {
        currentCategory = category;
        resetCategoryButtonStyles();
        
        // 更新选中按钮样式
        if ("all".equals(category)) {
            btnCategoryAll.setBackground(getDrawable(R.drawable.button_primary));
            btnCategoryAll.setTextColor(getResources().getColor(android.R.color.white));
        } else if ("new".equals(category)) {
            btnCategoryNew.setBackground(getDrawable(R.drawable.button_primary));
            btnCategoryNew.setTextColor(getResources().getColor(android.R.color.white));
        } else if ("hot".equals(category)) {
            btnCategoryHot.setBackground(getDrawable(R.drawable.button_primary));
            btnCategoryHot.setTextColor(getResources().getColor(android.R.color.white));
        } else if ("unlocked".equals(category)) {
            btnCategoryUnlocked.setBackground(getDrawable(R.drawable.button_primary));
            btnCategoryUnlocked.setTextColor(getResources().getColor(android.R.color.white));
        }
        
        // 过滤项目列表
        filterProjectsByCategory();
    }
    
    private void resetCategoryButtonStyles() {
        btnCategoryAll.setBackground(getDrawable(R.drawable.button_secondary));
        btnCategoryAll.setTextColor(getResources().getColor(android.R.color.darker_gray));
        
        btnCategoryNew.setBackground(getDrawable(R.drawable.button_secondary));
        btnCategoryNew.setTextColor(getResources().getColor(android.R.color.darker_gray));
        
        btnCategoryHot.setBackground(getDrawable(R.drawable.button_secondary));
        btnCategoryHot.setTextColor(getResources().getColor(android.R.color.darker_gray));
        
        btnCategoryUnlocked.setBackground(getDrawable(R.drawable.button_secondary));
        btnCategoryUnlocked.setTextColor(getResources().getColor(android.R.color.darker_gray));
    }
    
    private void filterProjectsByCategory() {
        if (adapter != null) {
            adapter.filterByCategory(currentCategory);
        }
    }
    
    @Override
    public void onProjectClick(Project project) {
        // 打开项目详情页面
        Intent intent = new Intent(this, ProjectDetailActivity.class);
        intent.putExtra("projectId", project.getId());
        startActivity(intent);
    }
    
    @Override
    public void onUnlockButtonClick(Project project) {
        // 使用DialogFragment显示解锁确认对话框
        ProjectDialogFragment dialogFragment = ProjectDialogFragment.newInstance(project);
        dialogFragment.setUnlockListener(this);
        dialogFragment.show(getSupportFragmentManager(), "UnlockProjectDialog");
    }
    
    private void showUnlockProjectDialog(Project project) {
        // 创建解锁确认对话框
        Dialog dialog = new Dialog(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_unlock_project, null);
        dialog.setContentView(dialogView);
        
        // 获取对话框视图
        ImageView projectImage = dialogView.findViewById(R.id.unlock_project_image);
        TextView projectTitle = dialogView.findViewById(R.id.unlock_project_title);
        TextView dialogMessage = dialogView.findViewById(R.id.dialog_message);
        TextView projectPrice = dialogView.findViewById(R.id.unlock_project_price);
        TextView currentBalance = dialogView.findViewById(R.id.current_balance);
        TextView balanceAfterUnlock = dialogView.findViewById(R.id.balance_after_unlock);
        TextView insufficientBalanceWarning = dialogView.findViewById(R.id.insufficient_balance_warning);
        Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
        Button btnConfirm = dialogView.findViewById(R.id.btn_confirm);
        
        // 设置项目信息
        ImageLoader.loadImage(this, project.getImageUrl(), projectImage);
        projectTitle.setText(project.getTitle());
        
        // 格式化金额
        NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.CHINA);
        String formattedPrice = currencyFormat.format(project.getPrice()).replace("CN¥", "¥");
        String formattedBalance = currencyFormat.format(userData.getBalance()).replace("CN¥", "¥");
        
        // 设置消息文本
        dialogMessage.setText(getString(R.string.project_unlock_message, formattedPrice));
        
        // 计算解锁后余额
        double balanceAfter = userData.getBalance() - project.getPrice();
        String formattedBalanceAfter = currencyFormat.format(balanceAfter).replace("CN¥", "¥");
        
        projectPrice.setText(formattedPrice);
        currentBalance.setText(formattedBalance);
        balanceAfterUnlock.setText(formattedBalanceAfter);
        
        // 检查余额是否足够
        boolean isBalanceSufficient = userData.getBalance() >= project.getPrice();
        
        if (!isBalanceSufficient) {
            insufficientBalanceWarning.setVisibility(View.VISIBLE);
            btnConfirm.setEnabled(false);
            btnConfirm.setAlpha(0.5f);
        } else {
            insufficientBalanceWarning.setVisibility(View.GONE);
            btnConfirm.setEnabled(true);
            btnConfirm.setAlpha(1.0f);
        }
        
        // 设置按钮点击事件
        btnCancel.setOnClickListener(v -> dialog.dismiss());
        
        btnConfirm.setOnClickListener(v -> {
            if (isBalanceSufficient) {
                // 执行解锁操作
                boolean unlockSuccess = MockDataManager.getInstance().unlockProject(
                        currentUsername, project.getId(), project.getPrice());
                
                if (unlockSuccess) {
                    // 更新用户数据和UI
                    loadUserData();
                    adapter.filterByCategory(currentCategory);
                    
                    Toast.makeText(this, R.string.project_unlock_success, Toast.LENGTH_SHORT).show();
                    
                    // 跳转到项目详情页
                    onProjectClick(project);
                } else {
                    // 检查失败原因
                    if (MockDataManager.getInstance().hasUnlockedProject(currentUsername, project.getId())) {
                        Toast.makeText(this, R.string.project_already_unlocked, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, R.string.balance_not_enough, Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                Toast.makeText(this, R.string.balance_not_enough, Toast.LENGTH_SHORT).show();
            }
            
            dialog.dismiss();
        });
        
        // 显示对话框
        dialog.show();
    }

    @Override
    public void onProjectUnlocked(int projectId) {
        // 项目解锁成功后刷新数据
        loadUserData();
        loadProjects();
        
        // 获取解锁的项目并打开详情页
        Project project = MockDataManager.getProjectById(projectId);
        if (project != null) {
            onProjectClick(project);
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 刷新用户数据
        loadUserData();
        // 刷新项目列表
        if (adapter != null) {
            adapter.filterByCategory(currentCategory);
        }
    }
}